package com.wanyl.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DbHandler implements HttpHandler {
    private static String Drivde="org.sqlite.JDBC";
    Connection connection;
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        String url = exchange.getRequestURI().toString();
        InputStream ins = exchange.getRequestBody();
//            ins.available()
        byte[] s=new byte[4096];
        ins.read(s);
        String body = new String(s);

        System.out.println("[ URL ] :"+url);

        if(url.contains("/read")){
            if(url.endsWith("/read")||url.endsWith("read/")){
                exchange.sendResponseHeaders(404,0);
                exchange.close();
                return;
            }

            String[] _tmp_url = url.split("\\/");
            String dbname = _tmp_url[_tmp_url.length - 1];
            System.out.println("生成sql中");
            String sql = "create table if not exists `"+dbname+"`(`field` varchar(255) PRIMARY KEY,`value` varchar(4096));";
            body=body.trim();
                    body=body.substring(1,body.length()-1);
            String sql2="select `field`,`value` from `" + dbname + "` where `field` in(" + body+")";
            System.out.println(sql2);
            sql_exec(sql);
            Map<String,Object> retdata=new HashMap<>();
            try {
                ResultSet rest = getDb().executeQuery(sql2);

//                System.out.println("rows:"+rest.getRow());

                while (rest.next()){
                    System.out.println(rest.getString(1));

                    retdata.put(rest.getString(1),URLDecoderString(rest.getString(2)));}
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            byte[] bin = JSONObject.toJSONString(retdata).getBytes("UTF-8");
//            System.out.println(new String(bin));
            exchange.sendResponseHeaders(200,0);
            exchange.getResponseBody().write(bin);
            exchange.close();
//            sql_query(sql2);

        }
        else if(url.contains("/write")){
//            System.out.println("已进入写");
            if(url.endsWith("/write")||url.endsWith("write/")){
//                System.out.println("url错误");
                exchange.sendResponseHeaders(404,0);
                exchange.close();
                return;
            }
//            System.out.println("url 规则检查完成");
//            data=new JSONObject(body);

            String[] _tmp_url = url.split("\\/");

            String dbname = _tmp_url[_tmp_url.length - 1];
            String sql = "create table if not exists `"+dbname+"`(`field` varchar(255) PRIMARY KEY,`value` varchar(4096));";
            sql_exec(sql);
//            String sql2="select * from `" + dbname + "` where `field` in " + body;
//            System.out.println("检查数据库完成");

            JSONObject o = JSON.parseObject(body);
            Set<String> key = o.keySet();

            String sql2="replace into `"+dbname+"`(`field`,`value`)values";


            for(String k : key){
                sql2+="('"+k+"','"+getURLEncoderString(o.getString(k))+"'),";
            }
            sql2=sql2.substring(0,sql2.length()-1);
            sql_exec(sql2);
//            System.out.println("执行完成");
            exchange.sendResponseHeaders(200,0);
            exchange.close();
        }else if(url.contains("/del")){
            if(url.endsWith("/del")||url.endsWith("del/")){
//                System.out.println("url错误");
                exchange.sendResponseHeaders(404,0);
                exchange.close();
                return;
            }
//            System.out.println("url 规则检查完成");
//            data=new JSONObject(body);

            String[] _tmp_url = url.split("\\/");

            String dbname = _tmp_url[_tmp_url.length - 1];
            String sql = "create table if not exists `"+dbname+"`(`field` varchar(255) PRIMARY KEY,`value` varchar(4096));";
            sql_exec(sql);
//            String sql2="select * from `" + dbname + "` where `field` in " + body;
//            System.out.println("检查数据库完成");

            body=body.trim();
            body=body.substring(1,body.length()-1);

            String sql2="delete from `"+dbname+"` where  `field` in("+body+");";

            sql_exec(sql2);
//            System.out.println("执行完成");
            exchange.sendResponseHeaders(200,0);
            exchange.close();
        }else if(url.contains("/clear")){
            if(url.endsWith("/clear")||url.endsWith("clear/")){
//                System.out.println("url错误");
                exchange.sendResponseHeaders(404,0);
                exchange.close();
                return;
            }
            String[] _tmp_url = url.split("\\/");
            String dbname = _tmp_url[_tmp_url.length - 1];
            String sql="drop table if exists `"+dbname+"`";
            exchange.sendResponseHeaders(200,0);
            exchange.close();
        }
    }
    public Statement getDb() {
        Statement statement;
        try {
            if(connection!=null)return connection.createStatement();

            Class.forName(Drivde);// 加载驱动,连接sqlite的jdbc
            if(!new File("data").exists())new File("data").mkdir();
            Connection connection = DriverManager.getConnection("jdbc:sqlite:data/data.db");//连接数据库zhou.db,不存在则创建
            statement = connection.createStatement(); //创建连接对象，是Java的一个操作数据库的重要接口
            return statement;
        }catch (Exception e){
            System.out.println("创建数据库失败");
            e.printStackTrace();
            System.exit(1);


        }
        return null;
    }
    public int sql_exec(String sql){
        System.out.println("执行SQL语句:"+sql);
        Statement t=getDb();
        try {
            int tx=  t.executeUpdate(sql);
            t.close();
            return tx;
        } catch (SQLException throwables) {
            System.out.println("执行sql语句错误");
            throwables.printStackTrace();
            try {
                t.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return 0;
        }
    }
    public String sql_query(String sql){
        Statement t=getDb();
        try {
            ResultSet data = t.executeQuery(sql);

            if(data==null){
                System.out.println("没有检测到数据1");
                t.close();
                return "";}

//            System.out.println("检测到行数为"+data.getRow()+"！");
//            data.get
//            if(data.getRow()==0) {t.close();return "";}
//            System.out.println("阶段1");
            if(!data.next()){t.close();return "";}
//            System.out.println("阶段2");
            String o = data.getString(1);
//            System.out.println("阶段3");
            data.close();
            t.close();
            return o;
        } catch (SQLException throwables) {
            try {
                t.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            System.out.println("执行sql语句错误");
            // throwables.printStackTrace();
        }
        return "";
    }
    public static String getURLEncoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLEncoder.encode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String URLDecoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}
